<template>
	<view class="">
		<view class="mainpadding ">
			<view class="flexbetween">
				<view class="flexleft">
					<view :class="currentsr==1?'select':'noselect'" style="margin-right: 15rpx;" @click="riclick">月
					</view>
					<view :class="currentsr==2?'select':'noselect'" style="margin-right: 15rpx;" @click="yueclick">年
					</view>
					<!-- <view :class="currentsr==3?'select':'noselect'" style="margin-right: 15rpx;" @click="nianclick">年
					</view> -->
				</view>
				<view class="selecttime_box radius flexcenter" style="width: 76%;" @click="messageTime.timeShow=true"
					v-if="currentsr!=3">
					<u-icon name="calendar" color="#F8CF39" size="20"></u-icon>
					<view class="xiaohei main_size margin_left1">{{start_time}}-{{end_time}}</view>
				</view>
			</view>
			<view class="flexbetween margin-top" v-if="currentsr==1">
				<view :class="classtype==1?'select':'noselect'" style="margin-right: 15rpx;" @click="changeClass(1)">營業額
				</view>
				<view :class="classtype==2?'select':'noselect'" style="margin-right: 15rpx;" @click="changeClass(2)">人數
				</view>
				<view :class="classtype==3?'select':'noselect'" style="margin-right: 15rpx;" @click="changeClass(3)">商品數
				</view>
				<view :class="classtype==4?'select':'noselect'" style="margin-right: 15rpx;" @click="changeClass(4)">
					平均客單
				</view>
				<view :class="classtype==5?'select':'noselect'" style="margin-right: 15rpx;" @click="changeClass(5)">
					平均商品
				</view>
			</view>
		</view>
		<!-- 日報表（表格） -->
		<template v-if="currentsr==1">
			<view class="table-container">
				<scroll-view class="table-scroll" scroll-x>
					<view class="table-outer" :style="{minWidth:100 * (dayList.length - 2) - 8+'px'}">
						<view class="table">
							<view class="table-header" :style="{width:dayList.length*90 + 100 + 'px'}">
								<view class="fixed-header">
									<view class="table-cell time-cell">時間段</view>
								</view>
								<view class="scrollable-header">
									<view class="table-cell day-cell" v-for="(item, index) in dayList"
										:key="'header-sales-' + index">
										{{ item.date }}
									</view>
								</view>
							</view>
							<!-- 表格内容 -->
							<view class="table-body">
								<view class="table-row" :style="{width:dayList.length*90 + 100 + 'px'}"
									v-for="(hour,hourindex) in tableList" :key="hourindex">
									<view class="fixed-cell">
										<view class="table-cell time-cell">{{hour.time}}</view>
									</view>
									<view class="scrollable-cells">
										<view class="table-cell month-cell" v-for="(item,index) in hour.list"
											:key="index">
											<text v-show="classtype==1">{{item.countmoney}}</text>
											<text v-show="classtype==2">{{item.ordernum}}</text>
											<text v-show="classtype==3">{{item.goodsnum}}</text>
											<text v-show="classtype==4">{{item.pjked_price}}</text>
											<text v-show="classtype==5">{{item.pjgoods_price}}</text>
										</view>
									</view>
								</view>
								<view class="table-row" :style="{width:dayList.length*90 + 100 + 'px'}"
									v-if="hourindex==0" v-for="(hour,hourindex) in tableList" :key="hourindex">
									<view class="fixed-cell">
										<view class="table-cell time-cell">統計</view>
									</view>
									<view class="scrollable-cells">
										<view class="table-cell month-cell" v-for="(item,index) in subAll"
											:key="index">
											<text v-show="classtype==1">{{item.countmoney}}</text>
											<text v-show="classtype==2">{{item.ordernum}}</text>
											<text v-show="classtype==3">{{item.goodsnum}}</text>
											<text v-show="classtype==4">{{item.pjked_price}}</text>
											<text v-show="classtype==5">{{item.pjgoods_price}}</text>
										</view>
									</view>
								</view>
							</view>
						</view>
					</view>
				</scroll-view>
			</view>
		</template>
		<!-- 月報表 （圖表）-->
		<template v-if="currentsr==2">
			<view class="" style="margin-top: 100rpx;height: 500px;">
				<qiun-data-charts type="line" :opts="opts" :chartData="chartData" />
			</view>
		</template>
		<!-- 年報表 （圖表）-->
		<template v-if="currentsr==3">
			<view class="" style="margin-top: 100rpx;height: 500px;">
				<qiun-data-charts type="line" :opts="opts" :chartData="chartData2" />
			</view>
		</template>
		<timePicker :messageTime="messageTime" @timeConfirm="timeConfirm"></timePicker>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				classtype: 1,
				currentsr: 1,
				start_time: "",
				end_time: "",
				chartData: {},
				chartData2: {},
				//您可以通过修改 config-ucharts.js 文件中下标为 ['line'] 的节点来配置全局默认参数，如都是默认参数，此处可以不传 opts 。实际应用过程中 opts 只需传入与全局默认参数中不一致的【某一个属性】即可实现同类型的图表显示不同的样式，达到页面简洁的需求。
				opts: {
					height: "800px",
					color: ["#FAC858", "#91CB74", "#1890FF", "#EE6666", "#73C0DE", "#3CA272", "#FC8452", "#9A60B4",
						"#ea7ccc"
					],
					padding: [15, 5, 0, 5],
					enableScroll: false,
					legend: {
						itemGap: 60,
						lineHeight: 40,
						fontSize: 16
					},
					xAxis: {
						axisLine: false, //x轴坐标轴线是否绘制
						disableGrid: true, //true不显示横线线，false显示横线
						fontColor: "#333", //文字颜色
						rotateLabel: true, //文字旋转
						rotateAngle: 40, //旋转角度
						marginTop: 8
					},
					yAxis: {
						gridType: "dash",
						dashLength: 2
					},
					extra: {
						line: {
							type: "straight",
							width: 2,
							activeType: "hollow"
						}
					}
				},
				dayList: [], //頂部日期
				tableList: [], //數據内容
				subAll:[],
				messageTime: {
					mode: "date",
					timeShow: false,
					title: "請選擇開始時間",
					maxDate: Number(new Date())
				},
			};
		},
		onLoad() {
			this.start_time = this.benyue();
			this.end_time = this.riqi(0);
			this.getdayInfo()
		},
		methods: {
			changeClass(val) {
				this.classtype = val
			},
			timeConfirm(e) {
				if (this.currentsr == 1) { //日篩選
					if (this.messageTime.title == "請選擇開始時間") {
						this.start_time = e
						setTimeout(() => {
							this.messageTime.title = "請選擇結束時間"
							this.messageTime.timeShow = true
						}, 100)
					} else {
						this.messageTime.title = "請選擇開始時間"
						this.end_time = e
					}
				}
				if (this.currentsr == 2) { //日篩選
					if (this.messageTime.title == "請選擇開始時間") {
						this.start_time = e
						setTimeout(() => {
							this.messageTime.title = "請選擇結束時間"
							this.messageTime.timeShow = true
						}, 100)
					} else {
						if (!this.isMoreThan12Months(this.start_time, e)) {
							this.http.toast("篩選時間最長不能超過12個月")
							setTimeout(() => {
								this.messageTime.timeShow = true
							}, 100)
							return false
						}
						this.messageTime.title = "請選擇開始時間"
						this.end_time = e
					}
				}
				this.getdayInfo()
			},
			isMoreThan12Months(date1, date2) {
				// 解析年月字符串为数组 [年, 月]
				const [year1, month1] = date1.split('-').map(Number);
				const [year2, month2] = date2.split('-').map(Number);

				// 计算两个日期之间的总月数差
				const monthDiff = Math.abs((year2 - year1) * 12 + (month2 - month1));

				// 判断是否超过12个月
				return monthDiff <= 12;
			},
			getdayInfo() {
				uni.showLoading({
					mask: true,
					title: "數據請求中"
				})
				this.http.request('/api/shop/orderReport', 'POST', {
					shop_id: uni.getStorageSync("shop_id"),
					start_time: this.start_time,
					end_time: this.end_time,
					type: this.currentsr
				}).then(res => {
					uni.hideLoading()
					if (this.currentsr == 1) {
						let arr = []
						for (let i = 0; i < 24; i++) {
							let infoarr = []
							res.data.forEach(item => {
								infoarr.push(item.data[i].data)
							})
							arr.push({
								time: res.data[0].data[i].name,
								list: infoarr
							})
						}
						this.tableList = arr
						this.dayList = res.data
						let data = []
						res.data.forEach(item => {
							let obj = {
								countmoney: 0,
								goodsnum: 0,
								ordernum: 0,
								pjgoods_price: 0,
								pjked_price: 0
							}
							item.data.forEach(cur => {
								obj.countmoney = Number(cur.data.countmoney) + Number(obj
									.countmoney)
								obj.goodsnum = Number(cur.data.goodsnum) + Number(obj
									.goodsnum)
								obj.ordernum = Number(cur.data.ordernum) + Number(obj
									.ordernum)
								obj.pjgoods_price = Number(cur.data.pjgoods_price) + Number(obj
									.pjgoods_price)
								obj.pjked_price = Number(cur.data.pjked_price) + Number(obj
									.pjked_price)
							})
							data.push(obj)
						})
						this.subAll = data
					}
					if (this.currentsr == 2) {
						let charts = {
							categories: [],
							series: [{
								name: "營業額",
								data: []
							}, {
								name: "人數",
								data: []
							}, {
								name: "商品數",
								data: []
							}, {
								name: "平均客單",
								data: []
							}, {
								name: "平均商品",
								data: []
							}, ]
						};
						res.data.forEach(item => {
							charts.categories.push(item.date)
							charts.series[0].data.push(item.data.countmoney)
							charts.series[1].data.push(item.data.ordernum)
							charts.series[2].data.push(item.data.goodsnum)
							charts.series[3].data.push(item.data.pjked_price)
							charts.series[4].data.push(item.data.pjgoods_price)
							// if(this.classtype==1){
							// 	charts.series[0].name = "營業額"
							// 	charts.series[0].data.push(item.data.countmoney)
							// }
							// if(this.classtype==2){
							// 	charts.series[0].name = "人數"
							// 	charts.series[1].data.push(item.data.ordernum)
							// }
							// if(this.classtype==3){
							// 	charts.series[0].name = "商品數"
							// 	charts.series[2].data.push(item.data.goodsnum)
							// }
							// if(this.classtype==4){
							// 	charts.series[0].name = "平均客單"
							// 	charts.series[3].data.push(item.data.pjked_price)
							// }
							// if(this.classtype==5){
							// 	charts.series[0].name = "平均商品"
							// 	charts.series[4].data.push(item.data.pjgoods_price)
							// }
						})
						this.chartData = JSON.parse(JSON.stringify(charts));
					}
				})
			},
			nianclick() {
				// 获取四年前和今年
				this.currentsr = 3
				uni.setNavigationBarTitle({
					title: "年報表"
				})
				let y = new Date().getFullYear(); //获取年份
				this.start_time = y - 4;
				this.end_time = y;
				this.getdayInfo()
			},
			yueclick() {
				// 获取本年第一個月和本月
				this.currentsr = 2
				uni.setNavigationBarTitle({
					title: "年報表"
				})
				let y = new Date().getFullYear(); //获取年份
				let m = new Date().getMonth() + 1; //获取月份
				this.messageTime.mode = "year-month"
				this.start_time = y + '-' + "01";
				this.end_time = y + '-' + (m > 9 ? m : ('0' + m));
				this.getdayInfo()
			},
			riclick() {
				// 获取本月第一天和今天
				uni.setNavigationBarTitle({
					title: "月報表"
				})
				this.messageTime.mode = "date"
				this.currentsr = 1
				this.start_time = this.benyue();
				this.end_time = this.riqi(0);
				this.getdayInfo()
			},
			// 昨天“-1”今天“0”明天“1”
			riqi(day) {
				let dd = new Date();
				dd.setDate(dd.getDate() + day);
				let y = dd.getFullYear();
				let m = dd.getMonth() + 1 < 10 ? "0" + (dd.getMonth() + 1) : dd.getMonth() + 1;
				let d = dd.getDate() < 10 ? "0" + dd.getDate() : dd.getDate();
				return y + "-" + m + "-" + d;
			},
			// 本月第一天
			benyue() {
				let y = new Date().getFullYear(); //获取年份
				let m = new Date().getMonth() + 1; //获取月份
				let d = '01'
				m = m < 10 ? '0' + m : m; //月份补 0
				return [y, m, d].join("-")
			},
		}
	};
</script>

<style scoped>
	.selecttime {
		width: 24rpx;
		height: 24rpx;
		background-size: 100% 100%;
	}

	.selecttime_text {
		font-size: 24rpx;
		font-weight: 500;
		color: #666666;
	}

	.selecttime_box {
		padding: 14rpx;
		border: 2rpx solid #F8CF39;
	}

	.select {
		padding: 15rpx 20rpx;
		border-radius: 20rpx;
		border: 1rpx solid #F8CF39;
		background-color: #F8CF39;
		font-size: 24rpx;
		font-family: PingFang SC-Bold, PingFang SC;
		font-weight: bold;
		color: #333;
	}

	.noselect {
		padding: 15rpx 20rpx;
		border-radius: 20rpx;
		border: 1rpx solid #999999;
		font-size: 24rpx;
		font-family: PingFang SC-Bold, PingFang SC;
		font-weight: bold;
		color: #999999;
	}
</style>


<style scoped>
	.table-container {
		border-radius: 8px;
		overflow: hidden;
		box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
	}

	.table-scroll {
		width: 100%;
		overflow-x: auto;
		/* 关键：设置滚动区域的高度，确保固定列能正确对齐 */
		overflow-y: auto;
	}

	.table-outer {
		position: relative;
	}

	.table-header {
		display: flex;
		background-color: #f9f9f9;
		border-bottom: 1px solid #eee;
	}

	.table-body {
		display: flex;
		flex-direction: column;
	}

	.table-row {
		display: flex;
		border-bottom: 1px solid #eee;
	}

	.table-row:last-child {
		border-bottom: none;
	}

	.table-row:nth-child(odd) {
		background-color: #f9f9f9;
	}

	/* 固定列样式 */
	.fixed-header,
	.fixed-cell {
		width: 100px;
		flex-shrink: 0;
		position: sticky;
		left: 0;
		z-index: 2;
		background-color: #f9f9f9;
	}

	.fixed-cell {
		background-color: inherit;
	}

	/* 可滚动内容区域 */
	.scrollable-header,
	.scrollable-cells {
		display: flex;
	}

	.table-cell {
		/* padding: 12px 8px; */
		height: 80rpx;
		line-height: 80rpx;
		text-align: center;
		font-size: 16px;
		font-weight: bold;
		border-right: 1px solid #eee;
		white-space: nowrap;
		min-width: 90px;
	}


	.time-cell {
		background-color: #f0f7ff;
		font-weight: bold;
		border-right: 2px solid #eee;
	}

	.day-cell {
		min-width: 90px;
	}

	/* 表头数据类型分组样式 */
	.scrollable-header .day-cell {
		background-color: #f0f0ff;
	}


	/* 周末单元格高亮 */
	.scrollable-header .day-cell:nth-child(6),
	.scrollable-header .day-cell:nth-child(7),
	.scrollable-header .day-cell:nth-child(13),
	.scrollable-header .day-cell:nth-child(14),
	.scrollable-header .day-cell:nth-child(20),
	.scrollable-header .day-cell:nth-child(21) {
		font-weight: bold;
	}

	.scrollable-cells .day-cell:nth-child(5),
	.scrollable-cells .day-cell:nth-child(6),
	.scrollable-cells .day-cell:nth-child(12),
	.scrollable-cells .day-cell:nth-child(13),
	.scrollable-cells .day-cell:nth-child(19),
	.scrollable-cells .day-cell:nth-child(20) {
		background-color: rgba(255, 255, 220, 0.5);
	}

	.weekly-summary {
		margin: 16px;
		padding: 16px;
		background-color: #fff;
		border-radius: 8px;
		box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
	}

	.summary-title {
		font-size: 16px;
		font-weight: bold;
		margin-bottom: 16px;
		color: #333;
		padding-bottom: 8px;
		border-bottom: 1px solid #eee;
	}

	.summary-grid {
		display: flex;
		justify-content: space-between;
	}

	.summary-card {
		flex: 1;
		text-align: center;
		padding: 16px 10px;
		margin: 0 5px;
		background-color: #f5f7fa;
		border-radius: 6px;
	}

	.card-label {
		font-size: 14px;
		color: #666;
	}

	.card-value {
		display: block;
		margin-top: 8px;
		font-size: 18px;
		font-weight: bold;
		color: #333;
	}
</style>